package com.dvd.djc.gdjc002;

import org.hibernate.Transaction;
import org.hibernate.TransactionException;

import com.dvd.dao.dvd.TDvd;
import com.dvd.dao.dvd.TDvdDAO;

/**
 * @author sjd
 *
 */
public class GDJC002Model {
	
	/**
	 * @param DvdId
	 * @param flag
	 * @return
	 * @throws Exception
	 */
	public TDvd searchDvdInfo(String id)
	{
		TDvdDAO dao=new TDvdDAO();		
		Transaction trans =dao.getSession().beginTransaction();
		TDvd dvd=null;
		dvd=dao.findById(id);
		trans.commit();
		dao.getSession().close();		
		return dvd;
	}
	
	
	/***
	 *@return (true) insert new dvd
	 *        (false) update dvd 
	 */
	 
	
	public boolean entryDvd(String flag,TDvd dvd)
	{
		boolean result=false;
		TDvd titledvd =this.findByTitle(dvd.getFDvdTitle());
		TDvdDAO dao=new TDvdDAO();		
		Transaction trans =dao.getSession().beginTransaction();
		if(titledvd == null || (titledvd!=null && titledvd.getFDvdId().equals(dvd.getFDvdId())))
		{
			System.out.println(flag);
			if(flag.equals("newentry"))
			{
				dao.getSession().save(dvd);
			}
			else
			{
				dao.getSession().update(dvd);
			}
			
			result=true;
		}
		else
		{
			result=false;
		}
		try
		{
		trans.commit();
		}catch(TransactionException e)
		{
			//do nothing
		}
		dao.getSession().close();
		return result;
	}
	
	
	
	public TDvd findByTitle(String title)
	{
		TDvdDAO dao=new TDvdDAO();		
		Transaction trans =dao.getSession().beginTransaction();
		TDvd dvd=null;
		dvd=dao.findByTitle(title);
		trans.commit();
		dao.getSession().close();		
		return dvd;
	}

}
